package com.df.config;

import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.backoff.BackoffStrategy;
import org.camunda.bpm.client.task.ExternalTask;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
@Slf4j
public class ExternalTaskClientConfig {
    
    @Value("${camunda.client.base-url}")
    private String baseUrl;
    
    @Value("${camunda.client.worker-id}")
    private String workerId;
    
    @Value("${camunda.client.max-tasks}")
    private Integer maxTasks;
    
    @Value("${camunda.client.async-response-timeout}")
    private Long asyncResponseTimeout;
    
    @Value("${camunda.client.lock-duration}")
    private Long lockDuration;
    
    @Value("${camunda.client.polling-interval:1000}")
    private Long pollingInterval;
    
    @Value("${camunda.client.connect-timeout:5000}")
    private Long connectTimeout;
    
    @Value("${camunda.client.read-timeout:10000}")
    private Long readTimeout;
    
    @Bean
    public ExternalTaskClient externalTaskClient() {
        log.info("=== 外部任务客户端配置 ===");
        log.info("服务器地址: {}", baseUrl);
        log.info("工作线程ID: {}", workerId);
        log.info("最大任务数: {}", maxTasks);
        log.info("异步响应超时: {}ms (任务锁定时间)", asyncResponseTimeout);
        log.info("锁定时间: {}ms (任务处理窗口)", lockDuration);
        log.info("轮询间隔: {}ms (任务获取频率)", pollingInterval);
        log.info("连接超时: {}ms", connectTimeout);
        log.info("读取超时: {}ms", readTimeout);
        log.info("==========================");
        
        return ExternalTaskClient.create()
            .baseUrl(baseUrl)
            .workerId(workerId)
            .maxTasks(maxTasks)
            .asyncResponseTimeout(asyncResponseTimeout)
            .lockDuration(lockDuration)
                .backoffStrategy(new BackoffStrategy() {
                    @Override
                    public void reconfigure(List<ExternalTask> list) {
                        // 根据获取到的任务数量动态调整
                        if (list.isEmpty()) {
                            log.debug("未获取到任务，保持当前轮询间隔");
                        } else {
                            log.debug("获取到 {} 个任务，减少轮询间隔", list.size());
                        }
                    }

                    @Override
                    public long calculateBackoffTime() {
                        // 减少回退时间，提高任务获取频率
                        return 50; // 50ms，非常短的间隔
                    }
                })
            .usePriority(true)  // 启用优先级
            .build();
    }
} 